/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tlr.device.rest;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.tfb.rong.Device;
import com.tfb.service.UserAssessmentI;
import com.tfb.service.utility.AppConst;
import static com.tfb.service.utility.HttpUtil.getUserDBID;
import com.tfb.service.utility.JsonUtil;
import com.tfb.service.utility.Utils;
import com.tlr.device.model.DeviceUserBind;
import com.tlr.device.model.Result;
import com.tlr.device.service.DeviceDatabaseService;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;

public abstract class AirDeviceResource {

    private static final Logger log = Logger.getLogger(AirDeviceResource.class);
    protected DeviceDatabaseService deviceService;
    protected UserAssessmentI userService;

    protected abstract void initDatabaseService();

    public Result<String> doEditBindDevice(HttpServletRequest request, String message) {
        try {
            initDatabaseService();
            JsonNode airDeviceInfo = JsonUtil.createJson(message);
            if (!airDeviceInfo.has("deviceMac")) {
                return new Result<>(500, "请输入设备编码");
            }
            if (!airDeviceInfo.has("nickname")) {
                return new Result<>(500, "请输入设备昵称");
            }
            String userID = getUserDBID(request);
            String deviceMac = airDeviceInfo.get("deviceMac").asText();
            String nickName = airDeviceInfo.get("nickname").asText();
            log.info("update bind: " + userID + ", " + deviceMac + ", " + nickName);
            deviceService.getDeviceUserBindMapper().update(new DeviceUserBind(userID, deviceMac, nickName));
            return new Result<>(0, "OK");
        } catch (Exception ex) {
            log.error(message);
            log.error(Utils.getFullException(ex));
            return new Result<>(500, "绑定失败,请联系管理员");
        }
    }

    public Result<String> doBindDevice(HttpServletRequest request, String message, String deviceName, int type) {
        try {
            initDatabaseService();
            JsonNode airDeviceInfo = JsonUtil.createJson(message);
            String userID = getUserDBID(request);
            if (!airDeviceInfo.has("deviceMac")) {
                return new Result<>(500, "请输入设备编码");
            }
            if (!airDeviceInfo.has("nickname")) {
                return new Result<>(500, "请输入设备昵称");
            }
            String deviceMac = airDeviceInfo.get("deviceMac").asText();
            if (!deviceService.getDeviceUserBindMapper().selectAllByUserIDAndDeviceID(userID, deviceMac).isEmpty()) {
                return new Result<>(500, "不能重复绑定到一个用户");
            }
            String nickName = airDeviceInfo.get("nickname").asText();
            Device device = new Device();
            device.setDevicemac(deviceMac);
            device.setDevicename(deviceName);
            device.setStatus(1);
            device.setDevicetype(type);
            if (null == deviceService.getDeviceByMac(deviceMac)) {
                deviceService.addDevice(device);
            } else {
                deviceService.getDeviceMapper().updateByDeviceMacSelective(device);
            }
            deviceService.getDeviceUserBindMapper().insert(new DeviceUserBind(userID, deviceMac, nickName));
            return new Result<>(0, "OK");
        } catch (Exception ex) {
            log.error(message);
            log.error(Utils.getFullException(ex));
            return new Result<>(500, "绑定失败,请联系管理员");
        }
    }

    public Result<String> updatePosition(String message) {
        try {
            log.info("position: " + message);
            JsonNode positionInfo = JsonUtil.createJson(message);
            initDatabaseService();
            Device device = new Device();
            device.setDevicemac(positionInfo.get("devicemac").asText());
            device.setDevicelang(positionInfo.get("longitude").asText());
            device.setDevicelati(positionInfo.get("latitude").asText());
            deviceService.getDeviceMapper().updateByDeviceMacSelective(device);
            return new Result<>(0, "OK");
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "更新位置信息错误，请联系管理员");
        }
    }

    public Result<JsonNode> getAQI() {
        try {
            Client client = Client.create();
            WebResource webResource = client.resource(AppConst.AQI_API);
            String respStr = webResource.accept(MediaType.APPLICATION_JSON).header(AppConst.AQI_API_HEADER, AppConst.AQI_API_KEY).get(String.class);
            log.info("Hike Control service returned:" + respStr);
            JsonNode json = JsonUtil.createJson(respStr);
            JsonNode aqiJson = json.get(AppConst.AQI_API_VER).get(0);
            if (aqiJson.has("status") && "ok".equals(aqiJson.get("status").asText())) {
                return new Result<>(0, "OK", aqiJson);
            } else {
                return new Result<>(500, respStr);
            }
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "读取AQI错误，请联系管理员");
        }
    }
}
